package io.hellsinger.filesystem.linux

import io.hellsinger.filesystem.checkScheme
import io.hellsinger.filesystem.linux.LinuxOperationOptions.Permission.EXECUTE_GROUP
import io.hellsinger.filesystem.linux.LinuxOperationOptions.Permission.EXECUTE_OTHER
import io.hellsinger.filesystem.linux.LinuxOperationOptions.Permission.EXECUTE_USER
import io.hellsinger.filesystem.linux.LinuxOperationOptions.Permission.READ_GROUP
import io.hellsinger.filesystem.linux.LinuxOperationOptions.Permission.READ_OTHER
import io.hellsinger.filesystem.linux.LinuxOperationOptions.Permission.READ_USER
import io.hellsinger.filesystem.linux.LinuxOperationOptions.Permission.WRITE_GROUP
import io.hellsinger.filesystem.linux.LinuxOperationOptions.Permission.WRITE_OTHER
import io.hellsinger.filesystem.linux.LinuxOperationOptions.Permission.WRITE_USER
import io.hellsinger.filesystem.linux.operation.DEFAULT_OPEN_MODE
import io.hellsinger.filesystem.linux.path.LinuxPath
import io.hellsinger.filesystem.path.Path
import java.io.File

fun String.toLinuxPath(): Path = LinuxPath(encodeToByteArray())

fun File.toLinuxPath(): Path = LinuxPath(absolutePath.encodeToByteArray())

fun Path.resolve(other: String): Path {
    checkScheme(LinuxOperationOptions.SCHEME)
    return resolve(other.encodeToByteArray())
}

fun String.toIntMode(): Int {
    if (isEmpty()) return DEFAULT_OPEN_MODE
    var mode = 0

    if (length == 3) {
        if (get(0) == 'R') mode = mode or READ_USER or READ_GROUP or READ_OTHER
        if (get(1) == 'W') mode = mode or WRITE_USER or WRITE_GROUP or WRITE_OTHER
        if (get(2) == 'X') mode = mode or EXECUTE_USER or EXECUTE_GROUP or EXECUTE_OTHER

        return mode
    }

    if (length == 9) {
        if (get(0) == 'r') mode = mode or READ_USER
        if (get(1) == 'w') mode = mode or WRITE_USER
        if (get(2) == 'x') mode = mode or EXECUTE_USER

        if (get(3) == 'r') mode = mode or READ_GROUP
        if (get(4) == 'w') mode = mode or WRITE_GROUP
        if (get(5) == 'x') mode = mode or EXECUTE_GROUP

        if (get(6) == 'r') mode = mode or READ_OTHER
        if (get(7) == 'w') mode = mode or WRITE_OTHER
        if (get(8) == 'x') mode = mode or EXECUTE_OTHER

        return mode
    }

    throw IllegalArgumentException("Unsupported length mode $length")
}
